import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout'
import Home from '@/views/home'
import Login from '@/views/login'
import UserList from '@/views/user'
import Roles from '@/views/roles'
import NotFound from '@/views/not-found/index'
import RightList from '@/views/right'
import OrderList from '@/views/order-list'
import { getToken } from '@/utils/auth'


// 解决重复点击同一个链接时,出现"NavigationDuplicated", 对异常进行捕获
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/404',
    name: '404',
    component: NotFound
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { title: '首页' }
  },
  {
    path: '/user',
    name: 'User',
    component: Layout,
    redirect: '/users',
    meta: { title: '用户管理' },
    children: [
      {
        path: '/users',
        component: UserList,
        meta: { title: '用户列表' }
      }
    ]
  },
  {
    path: '/right',
    name: 'Right',
    component: Layout,
    redirect: '/roles',
    meta: {
      title: '权限管理'
    },
    children: [
      {
        // 子路径添加'/', 会被视为根路径进行匹配 '/roles'匹配成功, 而不是'/right/roles'
        path: '/roles',
        name: 'Roles',
        component: Roles,
        meta: { title: '角色列表' }
      },
      {
        path: '/rights',
        name: 'Rights',
        component: RightList,
        meta: { title: '权限列表' }
      }
    ]
  },
  {
    path: '/order',
    name: 'Order',
    component: Layout,
    redirect: '/orders',
    meta: { title: '订单管理2' },
    children: [
      {
        path: '/orders',
        name: 'Orders',
        component: OrderList,
        meta: { title: '订单列表2' }
      }
    ]
  },
  {
    path: '/',
    redirect: '/user',
  },
  {
    path: '*',
    redirect: '/404'
  }
]

const router = new VueRouter({
  routes
})

// 全局守卫,拦截所有路由
router.beforeEach((to, from, next) => {

  // 白名单,不需要登录可以访问
  const whiteList = ['/login']
  const tokenStr = getToken()
  console.log('tokenStr', tokenStr)
  console.log('to', to.path)
  console.log('from', from.path)
  // 登录
  if (tokenStr) {
    if(to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 未登录
    // 判断在不在白名单中, 在就直接放行, 否则跳转到登录页面
    if(whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
